package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.bean.TradeSkuOrderBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimMapFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/3/20 09:44
 */
public class Dws_09_DwsTradeSkuOrderWindow_Cache extends BaseApp {
    public static void main(String[] args) {
        new Dws_09_DwsTradeSkuOrderWindow_Cache().init(
            4009,
            2,
            "Dws_09_DwsTradeSkuOrderWindow_Cache",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 封装到 pojo 中
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = parseToPojo(stream);
        // 2. 按照 order_detail_id 去重
        beanStream = distinctByOrderDetailId(beanStream);
        // 3. 分组开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStreamWithoutDims = windowAndAgg(beanStream);
    
        // 4. 补充维度信息
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStreamWithDims = joinDims(beanStreamWithoutDims);
        beanStreamWithDims.print();
    
        // 5. 写出到 clickhouse 中
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> joinDims(SingleOutputStreamOperator<TradeSkuOrderBean> beanStreamWithoutDims) {
        /*
        补充维度:
            sql 中: 使用 lookup join 进行补充
            
            流中: 只能自己手动补充
         */
        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoStream = beanStreamWithoutDims
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_sku_info";
                }
    
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSkuId();
                }
    
                @Override
                public void addDim(TradeSkuOrderBean bean, JSONObject dim) {
                    // {"ID": "", "SPU_ID": "", ...}
                    bean.setSkuName(dim.getString("SKU_NAME"));
                    bean.setSpuId(dim.getString("SPU_ID"));
                    bean.setTrademarkId(dim.getString("TM_ID"));
                    bean.setCategory3Id(dim.getString("CATEGORY3_ID"));
                }
            });
    
    
        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoStream = skuInfoStream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_spu_info";
                }
            
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSpuId();
                }
            
                @Override
                public void addDim(TradeSkuOrderBean bean, JSONObject dim) {
                    // {"ID": "", "SPU_ID": "", ...}
                    bean.setSpuName(dim.getString("SPU_NAME"));
                    
                }
            });
    
        SingleOutputStreamOperator<TradeSkuOrderBean> tmStream = spuInfoStream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_trademark";
                }
            
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getTrademarkId();
                }
            
                @Override
                public void addDim(TradeSkuOrderBean bean, JSONObject dim) {
                    // {"ID": "", "SPU_ID": "", ...}
                    bean.setTrademarkName(dim.getString("TM_NAME"));
                
                }
            });
    
        SingleOutputStreamOperator<TradeSkuOrderBean> c3Stream = tmStream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
            
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory3Id();
                }
            
                @Override
                public void addDim(TradeSkuOrderBean bean, JSONObject dim) {
                    // {"ID": "", "SPU_ID": "", ...}
                    bean.setCategory3Name(dim.getString("NAME"));
                    bean.setCategory2Id(dim.getString("CATEGORY2_ID"));
                
                }
            });
    
        SingleOutputStreamOperator<TradeSkuOrderBean> c2Stream = c3Stream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
            
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory2Id();
                }
            
                @Override
                public void addDim(TradeSkuOrderBean bean, JSONObject dim) {
                    // {"ID": "", "SPU_ID": "", ...}
                    bean.setCategory2Name(dim.getString("NAME"));
                    bean.setCategory1Id(dim.getString("CATEGORY1_ID"));
                
                }
            });
        
        return c2Stream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
        
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory1Id();
                }
        
                @Override
                public void addDim(TradeSkuOrderBean bean, JSONObject dim) {
                    // {"ID": "", "SPU_ID": "", ...}
                    bean.setCategory1Name(dim.getString("NAME"));
            
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
      return  beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(TradeSkuOrderBean::getSkuId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1,
                                                    TradeSkuOrderBean value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String skuId,
                                        Context ctx,
                                        Iterable<TradeSkuOrderBean> elements,
                                        Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
    
    
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> distinctByOrderDetailId(SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
       return beanStream
            .keyBy(TradeSkuOrderBean::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>() {
    
                private ValueState<TradeSkuOrderBean> state;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    ValueStateDescriptor<TradeSkuOrderBean> desc =
                        new ValueStateDescriptor<>("beanState", TradeSkuOrderBean.class);
                    StateTtlConfig ttlConfig = new StateTtlConfig.Builder(org.apache.flink.api.common.time.Time.seconds(10))
                        .updateTtlOnCreateAndWrite()
                        .build();
                    
                    desc.enableTimeToLive(ttlConfig);
                    state = getRuntimeContext().getState(desc);
                }
    
                @Override
                public void processElement(TradeSkuOrderBean currentBean,
                                           Context ctx,
                                           Collector<TradeSkuOrderBean> out) throws Exception {
                    TradeSkuOrderBean lastBean = state.value();
                    if (lastBean == null) { // 当前详情 id 第一条数据
                        out.collect(currentBean);
//                        state.update(currentBean);
                    }else{ // 不是第一条
                        // 用新的数据, 减去状态中的数据, 输出
                        lastBean.setOriginalAmount(currentBean.getOriginalAmount().subtract(lastBean.getOriginalAmount()));
                        lastBean.setActivityAmount(currentBean.getActivityAmount().subtract(lastBean.getActivityAmount()));
                        lastBean.setCouponAmount(currentBean.getCouponAmount().subtract(lastBean.getCouponAmount()));
                        lastBean.setOrderAmount(currentBean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        
                        out.collect(lastBean);
                        // 把新的数据存入到状态中
//                        state.update(currentBean);
                    }
                    state.update(currentBean);
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> parseToPojo(DataStreamSource<String> stream) {
      return  stream.map(new MapFunction<String, TradeSkuOrderBean>() {
            @Override
            public TradeSkuOrderBean map(String json) throws Exception {
                JSONObject obj = JSON.parseObject(json);
                return TradeSkuOrderBean.builder()
                    .skuId(obj.getString("sku_id"))
                    .originalAmount(obj.getBigDecimal("split_original_amount"))
                    .activityAmount(obj.getBigDecimal("split_activity_amount") == null ? new BigDecimal(0) : obj.getBigDecimal("split_activity_amount"))
                    .couponAmount(obj.getBigDecimal("split_coupon_amount") == null ? new BigDecimal(0) : obj.getBigDecimal("split_coupon_amount"))
                    .orderAmount(obj.getBigDecimal("split_total_amount"))
                    .ts(obj.getLong("ts") * 1000)
                    .orderDetailId(obj.getString("id"))
                    .build();
            }
            
        });
    }
}
/*
lookup join
    默认情况每次都去数据库查找.
    ttl:
优化 1:
    缓存
        查找逻辑: 先在缓存中查找, 如果查找直接返回, 没有查找到, 取数据库查找,然后存储到缓存.
        
缓存的选择?
    flink 的状态(map状态)
        好处:
            1. 快, 本地内存, 不需要网络, 读写速度极快
            2. 数据结构丰富, 可以根据需要选择合适的数据结构
        
        坏处:
            1. 额外占据了 flink 的内存, 影响 flink 的计算使用的内存
            2. 当维度发生变化的时候, 缓存中如果有这个维度,则无法及时更新
        

    redis(旁路缓存)
        好处:
            1. 数据结构丰富, 可以根据需要选择合适的数据结构
            2. 当维度发生变化的时候, 缓存中如果有这个维度,则可以及时更新
        
        
        坏处:
            1. 输出外部缓存, 每次读写都需要通过网络(尤其是同步查询),效率相比 flink 的状态较低
            
---------------------------
redis 的数据结构的选择?

string
    key                value
  表名+id               json 格式的字符串: {"id": "", ...}
  
  dim_sku_info:1        {"": "", ....}
  
  好处:
    1. 读写及其方便
    2. 单独的给每条维度设置 ttl
  坏处:
    1. key 特别多, 不方便管理, 容易与其他的 key 冲突
            可以单独给维度选择其他的库
            

list
    key                 value
    table               [json 格式字符串, ...]
    
    dim_sku_info       [...]
    
    好处:
        1. 可以特别少, 一张表一个 key
        2. 写比较方便
    坏处:
        1. 读不方便. 需要遍历 list 中所有维度, 然后找到 id 一致的
        2. 没有办法给每个维度单独设置 ttl
set
    不选

hash
    key              field    value
    dim_sku_info       1       json 格式字符串
                       2       json 格式字符串
                       ...
                       
     好处:
        1. 读写方便
        2. key 比较少
        
     坏处:
        1.无法单独给每个维度设置 ttl
        

zset
 
            


 */